<?php


namespace app\api\services;


use app\common\exception\ApiException;
use app\common\model\ClientModel;
use app\common\model\UserGroupModel;
use app\common\model\UserListModel;
use app\common\services\BaseService;

class GroupService extends BaseService
{
    /**
     * 创建群聊
     */
    static function CreateGroup($params){
        $groupId = $params['groupId'];
        //如果有群组id  则查询群组id对应的信息
        if($groupId){
            $groupInfo = UserGroupModel::findOne(['id'=>$groupId]);
        }

        // 将自己放在群成员首位
        array_unshift($params['groupUserList'],$params['uid']);
        //群
        $group_data = [
            'admin_id'=>$params['admin_id'],
            'admin_uid'=>$params['uid'],
            'name'=>$params['name']??'群聊',
            'member_number'=>count($params['groupUserList']),
        ];

        if(empty($groupInfo)){
            //创建群
            $groupId = UserGroupModel::create($group_data)['id'];
        }

        //向群组中 增加成员
        //获取当前群成员列表
        $userList = UserListModel::findAll([
            'type'=>2,
            'mid'=>$groupId,
        ],'uid');
        if($userList){
            $userList = array_column($userList,'uid');
        }
        // 筛选出不在群中的新成员
        $new_user_list = array_diff($params['groupUserList'],$userList);

//        dump($new_user_list);exit;
        //得到操作人的名称
        $nickname = ClientModel::findValue(['id'=>$params['uid']],'nickname');
        //循环加入群聊
        foreach ($new_user_list as $value){
            //需要先判断是否是双向好友
            $friendStatus = ClientService::getStatus($params['uid'],$value);
            $to_nickname = ClientModel::findValue(['id'=>$value],'nickname');

            if( $friendStatus!=3 ){
                //不是双向好友 不能拉入群聊中  仅提示给自己
                MessageService::sendMessage([
                    'uid'=>$params['uid'],
                    'mid'=>$groupId,
                    'msg'=>'您不是“'.$to_nickname.'”的好友，邀请进群失败',
                ],4);
                continue;
            }

            $userListData = [
                'uid'=>$value,
                'mid'=>$groupId,
                'type'=>2,
                'status'=>1,
                'is_show'=>1,
            ];
            UserListModel::create($userListData);

            // 将被要求的人 加入到群组中
            GatewayService::addGroupUser($value,$groupId);

            // 邀请人后，增加消息推送


            //自己不需要推送自己
            if($value !=$params['uid']){
                MessageService::sendMessage([
                    'uid'=>$params['uid'],
                    'mid'=>$groupId,
                    'msg'=>'邀请“'.$to_nickname.'”加入了群聊',
                ],3);
            }

        }
        $group_data['id'] = $groupId;//得到群组id

        //更新群成员数量 (因为有邀群失败的)
        $member_number = UserListModel::findCount(['type'=>2,'mid'=>$groupId]);
        UserGroupModel::updates(['id'=>$groupId],['member_number'=>$member_number]);
        $group_data['member_number'] = $member_number;

        return $group_data;
    }

    /**
     * 获取群组的群员的详细信息
     */
    static function GetGroupInfo($params){
        $uid = $params['uid'];
        $mid = $params['mid'];
        $model = new UserGroupModel();
        $where = [
            'id'=>$mid,
            'admin_id'=>$params['admin_id'],
        ];
        $list = $model->where($where)->with(['getUserList'])->find();
        if(empty($list)){
            return $list;
        }

        //循环获取 群组成员的详细信息
        foreach ($list->getUserList as $v){
            $v->getClientUid;
        }

        return $list;
    }

    /**
     * 删除群组某些成员
     * @param $params
     */
    static function delGroupUser($params){
        $groupId = $params['groupId'];
        $groupInfo = UserGroupModel::findOne(['id'=>$groupId]);
        if(empty($groupInfo)){
            throw new ApiException('群组不存在~');
        }
        if($groupInfo['admin_uid']!=$params['uid']){
            throw new ApiException('您不是管理员');
        }

        //循环移除群聊
        foreach ($params['groupUserList'] as $uid){
            $info = UserListModel::where([
                'type'=>2,
                'mid'=>$groupId,
                'uid'=>$uid,
            ])->find();
            if(!$info){
                continue;
            }
            $info->delete();
            $to_nickname = ClientModel::findValue(['id'=>$uid],'nickname');
            MessageService::sendMessage([
                'uid'=>$params['uid'],
                'mid'=>$groupId,
                'msg'=>'将“'.$to_nickname.'”移出了群聊',
            ],3);

            //从组中移除
            GatewayService::delGroupUser($uid,$groupId);
        }
        //更新成员数量
        $number = UserListModel::findCount(['type'=>2,'mid'=>$groupId]);
        UserGroupModel::updates(['id'=>$groupId],['member_number'=>$number]);
        $groupInfo['member_number'] = $number;
        return $groupInfo;
    }

    /**
     * 退出群
     */
    static function logoutGroup($params){
        $groupId = $params['groupId'];
        $uid = $params['uid'];

        $userList = UserListModel::findOne(['uid'=>$uid,'mid'=>$groupId,'type'=>2]);
        if(empty($userList)){
            throw new ApiException('您不在该群中~'.$groupId);
        }

        //查询群信息
        $groupInfo = UserGroupModel::findOne(['id'=>$groupId]);

        //更新群信息
        $upData = [
            'member_number'=>$groupInfo['member_number']-1,
        ];

        //2人以上 群主退群 需要重新指定新的群主，论资排辈
        if($groupInfo['admin_uid']==$uid && $groupInfo['member_number']>2){
            $new_admin_uid = UserListModel::findValue(['mid'=>$groupId,'type'=>2],'uid');
            $upData['admin_uid'] = $new_admin_uid;
        }


        if($upData['member_number']>0){
            // 更新群的相关信息
            UserGroupModel::updates(['id'=>$groupInfo['id']],$upData);
            // 推送退群消息给群主
            $to_nickname = ClientModel::findValue(['id'=>$uid],'nickname');
            MessageService::sendMessage([
                'uid'=>$upData['admin_uid'],
                'mid'=>$groupId,
                'msg'=>$to_nickname.'”退出了群聊',
            ],4);

        }else{
            //删除群
            UserGroupModel::destroy($groupInfo['id']);
            //解散群
            GatewayService::delGroup($groupId);
        }
        //个人退出群组
        UserListModel::destroy($userList['id']);
        //断开群组的通讯
        GatewayService::delGroupUser($userList['id'],$groupId);

        return true;
    }
}